// store/permission.js
import { constantRouterMap } from '@/router';
import { getAsyncRouterMap } from '@/api/user';
import Layout from '@/layout'


function loadView(view) { // 路由懒加载
  return (resolve) => require([`@/views/${view}/index`], resolve)
}

/**
 * 递归主要循环子元素
 * 
 * @param {父路径，用于加载路由} fdir
 * @param {路由集合本身} routers 
 */
function recursion(fdir, router) {
  if (router.children && router.children.length > 0) {
    router.children.forEach(item => {
      let path = item.perRoute;
      if (path && path != '#') {
        item.path = path;
        item.name = path;
        item.component = loadView(fdir + path)
      }
      recursion(fdir + path, item);
    });
  }
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.routers = constantRouterMap.concat(routers);
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return new Promise(resolve => {
        // const { authorities } = data;
        getAsyncRouterMap().then(response => {
          const asyncRouterMap = response.data;
          // 默认初始化左菜单
          var asyncRouter = [
            {
              path: '/',
              component: Layout,
              redirect: '/dashboard',
              children: [{
                path: 'dashboard',
                name: 'dashboard',
                component: () => import('@/views/dashboard/index'),
                meta: { title: '首页', icon: 'dashboard' }
              }]
            }
          ];
          asyncRouterMap.forEach(element => {
            let path = element.perRoute;
            if (path && path != '#') {
              console.log(path)
              element.path = "/" + path;
              element.name = path;
              element.component = loadView(path);
            }
            if (element.children && element.children.length > 0) {
              element.redirect = element.children[0].perRoute;
            }
            recursion(path + "/", element);
            asyncRouter[0].children.push(element);
          });
          commit('SET_ROUTERS', asyncRouter);
          resolve();
        });
      })
    }
  }
};

export default permission;